import { useLayoutEffect, useMemo, useRef } from "react";
import { ResourceList } from "../../Component/ResourceList";
import { useDelete } from "../../hooks/useDelete";
import { LibAppView } from "@/lib";
import { AdminRight } from "../../data/AdminPageAuth";
import { Button } from "antd";
import { FormattedMessage } from "react-intl";
import { PlusOutlined } from "@ant-design/icons";
import { SCIENCE_VENUE_BOOK_TYPES, SCIENCE_VENUE_STATUS, SCIENCE_VENUE_TYPES } from "./Data";
import ResourceStatus from "../../Component/ResourceStatus";
import { Modal, Input, message, Tag } from "antd";

interface IShowConfig {
    title: string|React.ReactNode;
    content: string|React.ReactNode;
    okText?: string;
    cancelText?: string;
    showConfirm?: boolean;
}
const showConfirm = (opt: IShowConfig) => {
    return new Promise((resolve, reject) => {
        if(opt.showConfirm) {
            Modal.confirm({
                title: opt.title,
                "content": <>{opt.content}</>,
                okText: opt.okText,
                cancelText: opt.cancelText,
                onOk: () => resolve(true),
                onCancel: () => reject(false)
            });
        } else {
            resolve(true);
        }
    });
};

const TextArea = Input.TextArea;

const ScienceVenueList = LibAppView.withService({
    "reqEndPoints": [
        { name: "accessRight", endPoint: "venue.approverRight" },
        { name: "firstApprover", endPoint: "venue.venueFirstApprover", "withoutErrorHandle": true },
        { name: "secondApprover", endPoint: "venue.venueSecondApprover", "withoutErrorHandle": true }
    ],
    "reqThrowException": false
})((props) => {
    const listRef = useRef<any>();
    const microApp = LibAppView.useMicroApp();
    const deleteAction = useDelete({
        endPoint: "venue.updateStatus",
        cancelEndPoint: "venue.updateStatus",
        updateEndPoint: "venue.updateStatus",
        data: {},
        listRef
    });
    const isApprover = useMemo(() => {
        const accessRight = (props.responseData as any)?.accessRight?.data;
        return accessRight?.firstApprover || accessRight?.secondApprover;
    }, [props.responseData]);
    const columns = useMemo(() => ([
        {
            title: "场馆名称",
            dataIndex: "title",
            width: 300,
            fixed: "left" as const,
        }, {
            title: "地址",
            dataIndex: "location",
            width: 240,
            render: (val: string, data: any) => {
                return val + data.addr;
            }
        }, {
            title: "登录账号",
            dataIndex: "ownerLoginName",
            width: 80
        },{
            title: "联系人",
            dataIndex: "contactor",
            width: 120
        }, {
            title: "联系电话",
            dataIndex: "mobile",
            width: 100
        }, {
            title: "预约类型",
            dataIndex: "bookType",
            width: 80,
            render: (bookType: string) => {
                const bookListType: string[] = bookType && bookType != "" ? JSON.parse(bookType) : [];
                return (<>
                    {
                        bookListType.map((item: string) => {
                            return <Tag key={item} color={"geekblue"}>{item}</Tag>;
                        })
                    }
                </>);
            }
        }, {
            title: "审批拒绝原因",
            dataIndex: "approveMsg",
            width: 200
        }, {
            title: "状态",
            dataIndex: "status",
            width: 120,
            render: (status: number) => {
                return (<>
                    <ResourceStatus status={status} dataMap={[
                        { value: 0, label: "编辑", color: "red" },
                        { value: 1, label: "已发布", color: "green" },
                        { value: 2, label: "待市科协审核", color: "orange" },
                        { value: 3, label: "待省科协审核", color: "#5ab2d8" },
                        { value: 4, label: "已失效", color: "grey" }
                    ]} />
                </>);
            }
        }, {
            title: "操作",
            dataIndex: "id",
            width: 160,
            fixed: "right" as const,
            render: (id: string, data: any) => {
                const approveProps = data.approveable && data.status !== 4 ? {} : { disabled: true };
                const deleteProps = data.deleteable && data.status===0 && data.status !== 4 ? {} : { disabled: true };
                const cancelProps = data.approveable || data.cancelable && data.status !== 4 ? {} : { disabled: true };
                const expireProps = isApprover  && data.status !== 4 ? {} : { disabled: true };
                return (<>
                    <Button type="primary" size="small" onClick={() => {
                        microApp.startJourney("editScienceVenueEdit", { state: { ...data } })
                    }}>{ data.status == 0 ? "编辑" : "查看" }</Button>
                    <Button type="dashed"  size="small" {...deleteProps} onClick={() => {
                        deleteAction.delete({...data, status: -1 });
                    }}>删除</Button>
                    <Button type="default" size="small" {...approveProps}
                        onClick={() => {
                            // status == 2 更新到 3
                            // status == 3 更新到 1
                            deleteAction.update({ ...data }, {
                                status: data.status == 3 ? 1 : 3
                            });
                        }}
                    >通过</Button>
                    <Button
                        type="default"
                        size="small"
                        {...cancelProps}
                        onClick={async() => {
                            const tmpState = { value: "" };
                            const accept = await showConfirm({
                                title: "拒绝通过审核",
                                content: (<>
                                    <span>审核不通过，请填写拒绝理由</span>
                                    <TextArea placeholder="请输入理由，字数不超过200字。" onChange={(e) => {
                                        tmpState.value = e.target.value;
                                    }}/>
                                </>),
                                showConfirm: data.approveable
                            });
                            accept && deleteAction.update({ ...data }, { status: 0, approveMsg: tmpState.value })
                        }}
                    >{ !data.approveable ? "撤销" : "拒绝"}</Button>
                    <Button
                        type="dashed"
                        size="small"
                        {...expireProps}
                        onClick={async() => {
                            const tmpState = { value: "" };
                            const accept = await showConfirm({
                                title: "失效场馆",
                                content: (<>
                                    <span>失效场馆信息将不可编辑，请填写失效详细原因：</span>
                                    <TextArea placeholder="请输入原因，字数不超过200字。" onChange={(e) => {
                                        tmpState.value = e.target.value;
                                    }}/>
                                </>),
                                showConfirm: true
                            });
                            accept && deleteAction.update({ ...data }, { status: 4, approveMsg: tmpState.value });
                    }}>失效</Button>
                </>);
            }
        }
    ]), [isApprover]);
    const searchFields = useMemo<Admin.IAdvancedField[]>(() => ([{
            label: "标题",
            name: "title",
            type: "Input"
        }, {
            label: "场馆类型",
            name: "venueType",
            type: "Select",
            data:  [
                { label: "全部", value: null },
                ...SCIENCE_VENUE_TYPES
            ]
        }, {
            label: "预约类型",
            name: "bookType",
            type: "Select",
            data: [
                { label: "全部", value: null },
                ...SCIENCE_VENUE_BOOK_TYPES
            ]
        }, {
            label: "状态",
            name: "status",
            type: "Select",
            data: [
                { label: "全部", value: null },
                ...SCIENCE_VENUE_STATUS
            ]
        }]), []);
     useLayoutEffect(() => {
        microApp.registeJourney({
            name: "editScienceVenueEdit",
            title: "Edit category",
            stepJourney: true,
            isTempJourney: true,
            steps: [{
                isMemoryPage: true,
                page: "admin.scienceVenueEdit"
            }]
        });
    },[]);
    return (
        <ResourceList
            refApi={listRef}
            tableColumns={columns}
            searchFields={searchFields}
            tableWidth={1000}
            listEndPoint={{
                endPoint: "venue.list",
                formatResponse: (resp: any) => {
                    const listData: any[] = resp.data || [];
                    return listData.map((item: any) => {
                        // const categoryData = categoryList.find((item2: any) => item2.value === item.type);
                        return {
                            ...item,
                            // typeTitle: categoryData?.label || "未知",
                        };
                    });
                }
            }}
            Operators={() => {
                return <>{isApprover ? (<AdminRight authRight="editable" mode="disabled">
                    <Button type="primary" onClick={() => {
                        microApp.startJourney("editScienceVenueEdit");
                    }}>
                        <PlusOutlined />
                        <span><FormattedMessage id="admin.pages.operate.add" /></span>
                    </Button>
                </AdminRight>) : <></>}
                <Button type="default"
                    onClick={async() => {
                        await props.withServiceApi.send({
                            endPoint: "venue.venueAccountAsync"
                        });
                        message.info("同步成功，可到用户列表查看信息。");
                    }}
                >
                    同步账号
                </Button>
                </>;
            }}
        />
    );
});

(ScienceVenueList as any).extract = () => {
    return (<h3>审核状态</h3>);
}

export default ScienceVenueList;
